package com.api.base.config.auth.service;

import com.api.base.model.SysPower;
import com.api.base.model.SysRole;
import com.api.base.model.User;
import com.api.base.service.SysPowerService;
import com.api.base.service.UserService;
import com.api.common.EmailUtil;
import com.api.common.JSONUtils;
import com.api.core.config.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DetailsServic implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private SysPowerService powerService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        /**
         * @params {u:username,t:type}
         */
        Map<String,Object> params =  JSONUtils.json2map(s);
        User user = userService.findBy("loginName",params.get("u"));
        if(user==null){
            throw new UsernameNotFoundException("User does not exist");
        }
        if(!user.getType().equals(params.get("t"))){
            throw new UsernameNotFoundException("无权登陆");
        }
        if (user.getDisable()){
            throw new UsernameNotFoundException("已经被禁用");
        }
        //角色
        List<String> roles =  userService.getRole(user.getId()).stream()
                .map(SysRole::getDescription).distinct()
                .collect(Collectors.toList());

        //用户信息
        Map<String,Object> info = userService.info(user.getId());

        //api 权限控制
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysPower> powers = powerService.getByUser(user.getId());
        if (powers.size() > 0) {
            for (SysPower p : powers) {
                authorities.add(new SimpleGrantedAuthority(p.getUrl()));
            }
        }

        user.setLogin(user.getLogin()+1);
        userService.update(user);
        return new AuthUser(user.getLoginName(), user.getPassword(), authorities, roles, user.getId(), user.getType(),user.getLogin(),user.getAvatar(),info.get("vipLevel")!=null ? info.get("vipLevel").toString() : "",!user.getDisable(),info);

    }
}
